import json

import requests
import re

headers = {
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive',
    'Content-Type': 'application/json',
    'Origin': 'https://fanyi.baidu.com',
    'Pragma': 'no-cache',
    'Referer': 'https://fanyi.baidu.com/mtpe-individual/multimodal?query=%E4%BD%A0%E5%A5%BD&lang=zh2en',
    'Sec-Fetch-Dest': 'empty',
    'Sec-Fetch-Mode': 'cors',
    'Sec-Fetch-Site': 'same-origin',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0',
    'accept': 'text/event-stream',
    'sec-ch-ua': '"Not)A;Brand";v="99", "Microsoft Edge";v="127", "Chromium";v="127"',
    'sec-ch-ua-mobile': '?0',
    'sec-ch-ua-platform': '"Windows"',
}


def translate(query, land='zh', to='en'):
    json_data = {
        'query': query,
        'from': land,
        'to': to,
        'reference': '',
        'corpusIds': [],
        'qcSettings': [
            '1',
            '2',
            '3',
            '4',
            '5',
            '6',
            '7',
            '8',
            '9',
            '10',
            '11',
        ],
        'needPhonetic': False,
        'domain': 'common'
    }
    response = requests.post('https://fanyi.baidu.com/ait/text/translate',
                             headers=headers,
                             json=json_data)
    try:
        data = re.findall("data: (.*?)\n", response.text)[4]
        dst = json.loads(data)['data']['list'][0]["dst"]
    except KeyError:
        data = re.findall("data: (.*?)\n", response.text)[3]
        dst = json.loads(data)['data']['list'][0]["dst"]
    return dst


if __name__ == '__main__':
   print(translate("北京"))
